package com.example.customer.controller;

import lombok.AllArgsConstructor;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * @author donniexue
 */
@RestController
@RequestMapping("/customer/eureka")
@AllArgsConstructor
public class CustomerEurekaController {

    private final DiscoveryClient discoveryClient;

    private final LoadBalancerClient loadBalancerClient;

    private final RestTemplate restTemplate;

    /**
     * 服务注册列表
     * @return
     */
    @GetMapping("/services")
    public String getService(){
        List<String> services = discoveryClient.getServices();
        StringBuffer result = new StringBuffer("eureka service list:");

        for (String service : services) {
            result.append(service + "\r\n");
        }
        return result.toString();
    }

    @GetMapping("/consumer")
    public String dc() {
        ServiceInstance serviceInstance = loadBalancerClient.choose("eureka-customer");
        String url = "http://" + serviceInstance.getHost() + ":" + serviceInstance.getPort() + "/customer/eureka/services";
        return restTemplate.getForObject(url, String.class);
    }

}
